<template>
  <div class="app-container">
    <!-- 搜索工作栏 -->
    <ContentWrap>
      <el-form
        class="-mb-15px"
        :model="queryParams"
        ref="queryFormRef"
        :inline="true"
        label-width="100px"
      >
        <el-form-item label="配件名称" prop="fittingName">
          <el-input
            v-model="queryParams.fittingName"
            placeholder="请输入配件名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="设备名称" prop="deviceName">
          <el-input
            v-model="queryParams.deviceName"
            placeholder="请输入设备名称"
            clearable
            @keyup.enter="handleQuery"
            class="!w-240px"
          />
        </el-form-item>
        <el-form-item label="配件状态" prop="fittingStatus">
          <el-select
            v-model="queryParams.fittingStatus"
            placeholder="请选择配件状态"
            clearable
            class="!w-240px"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.BMS_FITTING_STATUS)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
          <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
          <el-button
            type="primary"
            plain
            @click="openForm('create')"
            v-hasPermi="['bms:fitting:create']"
          >
            <Icon icon="ep:plus" class="mr-5px" /> 新增
          </el-button>
        </el-form-item>
      </el-form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap>
      <el-table v-loading="loading" :data="fittingList">
        <el-table-column label="配件名称" align="center" prop="fittingName" />
        <el-table-column label="配件型号" align="center" prop="fittingModel" />
        <el-table-column label="配件状态" align="center" prop="fittingStatus">
          <template #default="scope">
            <dict-tag :type="DICT_TYPE.BMS_FITTING_STATUS" :value="scope.row.fittingStatus" />
          </template>
        </el-table-column>
        <el-table-column label="绑定日期" align="center" prop="bindTime" width="180">
          <template #default="scope">
            <span v-if="scope.row.bindTime">{{
              formatDate(new Date(scope.row.bindTime), 'YYYY-MM-DD')
            }}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="有效期" align="center" prop="expired" />
        <el-table-column label="失效日期" align="center">
          <template #default="scope">
            <span
              v-if="scope.row.bindTime && scope.row.expired"
              :class="getExpireDateClass(scope.row.bindTime, scope.row.expired)"
            >
              {{ calculateExpireDate(scope.row.bindTime, scope.row.expired) }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="绑定设备" align="center" prop="deviceName">
          <template #default="scope">
            <span v-if="scope.row.deviceId">
              <el-link
                type="primary"
                :underline="true"
                :href="`/bms/device/index?id=${scope.row.deviceId}`"
                >{{ scope.row.deviceName }}</el-link
              >
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              type="text"
              icon="Edit"
              @click="openForm('update', scope.row.id)"
              v-hasPermi="['bms:fitting:update']"
              >修改</el-button
            >
            <el-popconfirm title="是否确认移除该配件？" @confirm="handleDelete(scope.row)">
              <template #reference>
                <el-button type="text" icon="Delete" v-hasPermi="['bms:fitting:delete']"
                  >删除</el-button
                >
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNo"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </ContentWrap>

    <!-- 添加或修改用户对话框 -->
    <FittingForm ref="formRef" @success="getList" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { ElMessage } from 'element-plus'
import { dateFormatter2, formatDate } from '@/utils/formatTime'
import * as FittingApi from '@/api/bms/fitting'
import FittingForm from './FittingForm.vue'

defineOptions({ name: 'BmsFitting' })

const queryFormRef = ref()

const loading = ref(false)
const total = ref(0)
const fittingList = ref([])

// 查询参数扩展
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  fittingName: '',
  deviceName: '',
  fittingStatus: undefined
})

// 重置查询参数
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

// 获取配件列表
const getList = async () => {
  loading.value = true
  try {
    const data = await FittingApi.getFittingPage(queryParams)
    fittingList.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

// 删除按钮操作
const handleDelete = async (row) => {
  const id = row.id
  await FittingApi.deleteFitting(id).then(() => {
    getList()
    ElMessage.success('删除成功')
  })
}

// 计算失效日期
const calculateExpireDate = (changeTime: string, expired: number) => {
  if (!changeTime || expired === undefined || expired === null) return '-'

  try {
    const date = new Date(changeTime)
    // 将失效天数添加到更换日期
    date.setDate(date.getDate() + expired)
    return formatDate(date, 'YYYY-MM-DD')
  } catch (error) {
    console.error('计算失效日期出错:', error)
    return '-'
  }
}

// 根据失效日期获取样式类名
const getExpireDateClass = (changeTime: string, expired: number) => {
  if (!changeTime || expired === undefined || expired === null) return ''

  try {
    const today = new Date()
    today.setHours(0, 0, 0, 0) // 设置为今天的开始时间

    const expireDate = new Date(changeTime)
    expireDate.setDate(expireDate.getDate() + expired)

    // 计算失效日期与当前日期的天数差
    const diffTime = expireDate.getTime() - today.getTime()
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))

    // 已失效
    if (diffDays < 0) {
      return 'text-danger'
    }

    // 即将失效（3天内）
    if (diffDays <= 3) {
      return 'text-warning'
    }

    return ''
  } catch (error) {
    console.error('计算失效日期样式出错:', error)
    return ''
  }
}

getList()
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  margin-bottom: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.card-header:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

@media (max-width: 768px) {
  .card-header {
    padding: 12px;
    flex-direction: column;
    gap: 8px;
  }
}

.el-select {
  width: 100%;
}

.text-danger {
  color: #f56c6c;
  font-weight: bold;
}

.text-warning {
  color: #e6a23c;
  font-weight: bold;
}
</style>
